<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="layui-row">
        <div class="layui-col-md6 select-depot-storage">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          />
          <page-table
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            v-model:data="tableInfo.data"
            :api="api"
            ref="productTable"
            v-model:ref-obj="tableInfo.ref"
            class="productTable"
            :isCompareChecked="true"
            :reserveSelection="true"
            :listenHeight="false"
            v-model:query="filterInfo.query"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            :highlight-row="highlightRow"
            :check-box="checkBox"
            @handleEvent="handleEvent"
          >
          </page-table>
        </div>
        <div class="layui-col-md6" style="padding-left: 20px">
          <el-table
            :data="rightList"
            border
            header-row-class-name="tableHeader"
            :max-height="255"
            ref="batchNumberTable"
            style="width: 100%; margintop: 40px"
          >
            <el-table-column type="index" width="50" />
            <el-table-column
              prop="licenseNumber"
              :label="'证号\n生产厂家'"
              align="center"
            >
              <template slot-scope="scope">
                <p>{{ scope.row.licenseNumber || '-' }}</p>
                <p>{{ scope.row.brandName || '-' }}</p>
              </template>
            </el-table-column>
            <el-table-column
              prop="commonName"
              :label="'通用名称\n编码\n别名'"
              align="center"
            >
              <template slot-scope="scope">
                <p>{{ scope.row.commonName || '-' }}</p>
                <p>{{ scope.row.productCode || '-' }}</p>
                <p>{{ scope.row.alias || '-' }}</p>
              </template>
            </el-table-column>
            <el-table-column
              prop="type"
              :label="'产品类型\n条码类型\n产品分类'"
              align="center"
            >
              <template slot-scope="scope">
                <p>{{ scope.row.productTypeValue || '-' }}</p>
                <p>{{ scope.row.codeTypeValue || '-' }}</p>
                <p>{{ scope.row.productCategoryValue || '-' }}</p>
              </template>
            </el-table-column>
            <el-table-column
              prop="standard"
              :label="'规格\n计量单位'"
              align="center"
            >
              <template slot-scope="scope">
                <p>{{ scope.row.standard || '-' }}</p>
                <p>{{ scope.row.unitName || '-' }}</p>
              </template>
            </el-table-column>
            <el-table-column
              prop="qty"
              label="申购数量"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <p>
                  {{ scope.row.qty ? $fn.qtyFormatter(scope.row.qty) : '0' }}
                </p>
              </template>
            </el-table-column>
          </el-table>
          <!--          <div class="paginationBox">-->
          <!--            <el-pagination-->
          <!--              :background="true"-->
          <!--              @size-change="sizeChange"-->
          <!--              @current-change="currentChange"-->
          <!--              @prev-click="currentChange"-->
          <!--              @next-click="currentChange"-->
          <!--              :current-page="curPage"-->
          <!--              :page-sizes="pageSizeList"-->
          <!--              :page-size="pageSize"-->
          <!--              layout="total, sizes, prev, pager, next, jumper"-->
          <!--              :total="tableTotal"-->
          <!--            />-->
          <!--          </div>-->
        </div>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="SelectPurchApplication">
import PageDialog from '../PageDialog/index'
import PageTable from '../PageTable/index'
import PageFilter from '../PageFilter/index'
import {
  getPurchApplicationPage,
  getPurchApplicationDetailAll,
} from '@/api/purch'
import * as _ from 'lodash'
import { getDeptAll } from '@/api/core'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: true,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getPurchApplicationPage,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  defaultSelect: {
    type: Array,
    default: function () {
      return []
    },
  },
  deptId: {
    type: Number,
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    ...props.query,
    sort: 'create_time desc',
    statusMult: 'pend_submit,pend_check',
    deptAuth: 'deptId',
    // deptId: this.deptId
  },
  list: [
    {
      label: '部门',
      value: 'deptId',
      type: 'slip-select',
      api: getDeptAll,
      query: { sort: 'create_time desc', deptAuth: 'id' },
      clearable: false,
      event: search,
    },
    { type: 'input', label: '单号', value: 'orderNoLike', event: search },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  height: '70%',
  ref: {},
  data: [],
  fieldList: [
    { label: '申购单号', value: 'orderNo' },
    { label: '部门', value: 'deptName' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
  ],
})
const rightList = ref([])
// 弹窗相关
const dialogInfo = ref({
  title: '选择申购单',
  btLoading: false,
  width: '75%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: false,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref([])
const clickRow = ref({})
const tableCheckSelectRow = ref([])
const purchApplicationId = ref('')
const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

function search() {
  if (clickRow.value.hasOwnProperty('id')) {
    proxy.$refs['productTable'].setCurrentRow(clickRow.value)
  }
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 获取右侧批号列表
function getRightList() {
  let params = {
    purchApplicationId: purchApplicationId.value,
  }
  getPurchApplicationDetailAll(params).then((res) => {
    if (res && res.success) {
      if (res.data) {
        rightList.value = res.data
        // this.curPage = res.curPage
        // this.pageSize = res.pageSize
        // this.tableTotal = res.total
      } else {
        rightList.value = []
      }
    }
  })
}
// currentChange(page) {
//   this.curPage = page
//   this.getRightList()
// },
// sizeChange(pageSize) {
//   this.pageSize = pageSize
//   this.curPage = 1
//   this.getRightList()
// },
function save() {
  // if(selectRow.value && selectRow.value.length){
  handleClose()
  emits('callback', selectRow.value)
  // }else {
  //   this.$message({
  //     type: 'warning',
  //     duration: 3500,
  //     showClose: true,
  //     message: '请选择订单'
  //   })
  // }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      purchApplicationId.value = data.id
      clickRow.value = data
      getRightList()
      break
    case 'tableCheck':
      if (data.length) {
        // let mapNew = _.groupBy(data,"id");
        // let mapOld =  _.groupBy(selectRow.value,"id")
        // let dataArr = _.groupBy(this.tableInfo.data,"id")
        // let spliceData = []
        // let mapTmpAdd = _.keys(mapNew).filter(x=> !_.has(mapOld, x));
        // if(mapTmpAdd && mapTmpAdd.length === 1) {
        //   spliceData = dataArr[mapTmpAdd[0]]
        //   if(spliceData && spliceData.length) {
        //     clickRow.value = spliceData[0]
        //     let filterArr = data.filter(item => item.deptId !== spliceData[0].deptId)
        //     if(filterArr.length) {
        //       filterArr.forEach(item => {
        //         proxy.$refs['productTable'].toggleRowSelection(item, false);
        //       })
        //     }
        //     data = data.filter(item => item.deptId === spliceData[0].deptId)
        //   }
        // }
        selectRow.value = data
      } else {
        clearSelectData()
      }
      dialogInfo.value.btList[1].disabled = data.length > 0 ? false : true
      break
  }
}
function clearSelectData() {
  rightList.value = []
  // clickRow.value = {}
  selectRow.value = []
  purchApplicationId.value = ''
  proxy.$refs['productTable'].clearSelection()
  // this.curPage = 1
  // this.pageSize = 0
  // this.tableTotal = 0
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}

onMounted(() => {
  proxy.$nextTick(() => {
    search()
    if (prpps.defaultSelect.length) {
      prpps.defaultSelect.forEach((item) => {
        proxy.$refs['productTable'].toggleRowSelection(item, true)
      })
    }
  })
})
</script>

<style scoped lang="scss">
.productTable :deep(.el-table__header-wrapper) .el-checkbox {
  display: none;
}
:deep(.select-depot-storage) {
  height: 355px;
  display: flex;
  flex-direction: column;
}
</style>
